import { useContext, useRef, useState } from "react"
import { useDrag, useDrop } from "react-dnd"
import { DesignFrameworkContext } from "./context"
import lodash from "lodash"
import './index.less'
import { CopyOutlined, DeleteOutlined } from "@ant-design/icons";
import { Space } from "antd";
import { addIdProperty, getComponentConfig, getId } from "./utils"
import { QuickCodeContext } from "../render/context"



const RcDrag = ({ children, index, $schema }: any) => {
  const ref = useRef(null)
  const [direction, setDirection] = useState('')
  const { registerComponents } = useContext(QuickCodeContext)
  const { selectItem, activeItem, moveItemById, deleteItemById } = useContext(DesignFrameworkContext)
  const noAction = getComponentConfig(registerComponents[$schema.component], 'noAction')
  //  registerComponents[$schema.component] ? registerComponents[$schema.component].noAction : false
  const [{ isDragging }, drag] = useDrag(
    () => ({
      type: '111',
      item: { id: $schema.id, index },
      collect: (monitor) => ({
        isDragging: monitor.isDragging(),
      }),
      canDrag(monitor) {

        return $schema.component != 'Placeholder'
      },
      end: (item, monitor) => {

        return false
      },
    }),
    [index],
  )
  const [m, drop] = useDrop(
    () => ({
      accept: getComponentConfig(registerComponents[$schema.component], 'canDrop') === false ? '' : '111',
      collect: (monitor) => ({
        isOver: monitor.isOver(),
        canDrop: monitor.canDrop(),
        isOverCurrent: monitor.isOver({ shallow: true }),
      }),
      // canDrop(item, monitor) {
      //   // console.log('devdev',$schema.component)
      //   return $schema.component==='QuickTabsPanel'
      // },
      drop(item2: any, monitor) {
        const didDrop = monitor.didDrop()

        if (didDrop) {

          return
        }
        //   if($schema.component==='QuickTabsPanel'){
        //     return
        //  }

        const hoverBoundingRect = ref.current.getBoundingClientRect();
        const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
        const clientOffset = monitor.getClientOffset();
        const hoverClientY = clientOffset.y - hoverBoundingRect.top;
        let direction = ''
        if (hoverClientY < hoverMiddleY) {
          // 拖动元素在目标元素上方
          direction = 'up'
        }
        else if (hoverClientY > hoverMiddleY) {
          // 拖动元素在目标元素下方
          direction = 'down'
        } else {
          direction = ''
        }
        moveItemById({
          originalId: item2.id,
          targetId: $schema.id,
          item: item2,
          addIndex: direction == 'up' ? -1 : 0
        })
        console.log({ $schema, })
      },
      hover(item: any, monitor) {

        // if(!monitor.canDrop){
        //   return
        // }

        const hoverBoundingRect = ref.current.getBoundingClientRect();
        const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
        const clientOffset = monitor.getClientOffset();
        const hoverClientY = clientOffset.y - hoverBoundingRect.top;

        if (hoverClientY < hoverMiddleY) {
          // 拖动元素在目标元素上方
          setDirection('up')
        }
        else if (hoverClientY > hoverMiddleY) {
          // 拖动元素在目标元素下方
          setDirection('down')
        } else {
          setDirection('')
        }

        return false
      },
    }),
    [moveItemById],
  )
  const onSelect = (e, item) => {
    if (item.id === activeItem.id || noAction) {
      return
    }
    e.stopPropagation();
    setDirection('')
    selectItem({ ...item })
  }

  const onCopy = () => {
    let _item = lodash.cloneDeep($schema)
    moveItemById({
      targetId: $schema.id,
      item: addIdProperty(_item),
    })
  }
  const onDel = () => {
    deleteItemById($schema.id)
    selectItem({})
  }
  const isActive = activeItem.id == $schema.id
  return <div
    className={`${noAction ? 'no-action-component' : ''}  draggable-item ${isDragging ? 'dragging-item' : ''} ${isActive ? 'design-active' : ''} ${(direction && m.isOverCurrent) ? `draggable-${direction}` : ''}`}
    ref={(node) => {

      drag(drop(node))
    }}
  >

    {/* {direction === 'up' && m.isOverCurrent ? <div style={{ height: 20, border: '2px solid blue', position: 'relative', width: '100%' }}></div> : null} */}

    <div
      className={`design-item`}
      onClick={(e) => { onSelect(e, $schema) }}
      ref={ref}
    // style={{
    //   opacity: isDragging ? 0.5 : 1,
    //   padding: 10, border: activeItem.id == item.id ? '2px solid #1890ff' : '1px dashed #40a9ff', margin: 5
    // }}
    >
      <div className="draggable-helpers ">
        <Space>
          <span>{$schema.component}</span>
          {
            $schema.component != 'AppContainer' ? <>
              <DeleteOutlined onClick={onDel} />
              <CopyOutlined onClick={onCopy} />
            </> : null
          }

        </Space>
      </div>

      {children}

    </div>

    {/* {direction === 'down' && m.isOverCurrent ? <div style={{ height: 20, border: '2px solid red', position: 'relative', width: '100%', top: '0px' }}></div> : null} */}
  </div>
}
export default RcDrag